﻿using CloverNet.Authorization.Demo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CloverNet.Authorization;

namespace CloverNet.Authorization.Demo.Controllers
{
    [AllowAnonymous]
    public class AccountController : Controller
    {
        // GET: Account
        public ActionResult LogIn(string refer)
        {
            if (AuthorizationManager.IsLogIn)
            {
                return RedirectToAction("Index", "Home");
            }

            var redirect = !string.IsNullOrEmpty(refer) && Url.IsLocalUrl(new UriBuilder(refer).Uri.AbsolutePath);
            if (redirect)
            {
                TempData["refer"] = refer;
            }
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult LogIn(UserModel model)
        {
            if (ModelState.IsValid)
            {
                if (model.UserName == "admin" && model.Password == "123456")
                {
                    AuthorizationManager.LogIn(model);

                    var refer = TempData["refer"];
                    if (refer != null)
                    {
                        return Redirect(refer.ToString());
                    }
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", "用户名或者密码不正确!");
                }
            }
            return View(model);
        }

        public ActionResult LogOut()
        {
            AuthorizationManager.LogOut();
            return RedirectToAction("LogIn", "Account");
        }

        public ActionResult Register()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                AuthorizationManager.LogIn(model);
                return RedirectToAction("Index", "Home");
            }
            return View(model);
        }
    }
}